#include <stdio.h>
#include <stdlib.h>




char code(const char c, const int d) {
//	if ( ( (int)c >= 'A' && (int)c <= 'Z' ) || ( (int)c >= 'a' && (int)c <= 'z' ) || ( (int)c >= '0' && (int)c <= '9' ) ) {
//		return c+d;
//	}
//	else {
//		return c;
//	}
	return c+d;
}


char decode(const char c, const int d) {
//	if ( ( (int)c >= 'A'+d && (int)c <= 'Z'+d ) || ( (int)c >= 'a'+d && (int)c <= 'z'+d ) || ( (int)c >= '0'+d && (int)c <= '9'+d ) )	{
//		return c-d;
//	}
//	else {
//		return c;
//	}
	return c-d;
}


int main(int argc, char *argv[]) {
	
	if (argc < 2) {
		printf("usage : ./generator <licence request file> [<expiration date : mmddyyyy>]");
		return EXIT_FAILURE;
	}
	else {
		
		// args[1] : licence request file
		// args[2] (optionnal) : expiration_date (default = 20131231)
		//
		// <nom package appli>.<ID carte SIM>.<date expiration yyyymmdd>
		
		FILE *in, *out;

		in = fopen(argv[1], "r");
		out = fopen("Licence", "wb");
		if( in == NULL )
		{
			printf("no such file");
			return EXIT_FAILURE;
		}
		
		// Size calculation
		int length = 0;
		while (fgetc(in) != EOF) length++;
		
		char licence[length+9];
		rewind(in);
		
		char c = fgetc(in);
		
		// Caesar code (+8)
		
		// Request coding
		while (c != EOF) {
			fputc(code(c, 8), out);
			c = fgetc(in);
		}
		
		fputc(code('/', 8), out);
		
		// Append expiration date coding
		if (argc == 3) {
			int i;
			for (i=0; i<8; i++) {
				fputc(code(argv[2][i], 8), out);
			}
		}
		else {
			int i;
			char exp[8] = "20131231";
			for (i=0; i<8; i++) {
				fputc(code(exp[i], 8), out);
			}
		}
		
		fclose(out);
		fclose(in);
		
		
		// DECODE TEST
		printf("\n\ndecode : ");
		FILE *read = fopen("Licence", "r");
		int i;
		for (i=0; i<length+9; i++) {
			printf("%c", decode(fgetc(read), 8));
		}
		fclose(read);
		// DECODE TEST fin
		
		
		
		return EXIT_SUCCESS;
	}
	
}